#include "configRequest.h"

    size_t configCallback(void *contents, size_t size, size_t nmemb, void *userp) {
    size_t realsize = size * nmemb;
    // 这里可以处理获取到的数据，比如存储到文件或者其他操作
    char * result = (char *)contents;
    printf("%s\n",result);
    
    cJSON *jsonstr= cJSON_Parse(result);
    if(jsonstr!=NULL){
        cJSON *successRoot = cJSON_GetObjectItemCaseSensitive(jsonstr,"success");
        cJSON *codeRoot = cJSON_GetObjectItemCaseSensitive(jsonstr,"code");
        cJSON *messageRoot = cJSON_GetObjectItemCaseSensitive(jsonstr,"message");
        
        if(cJSON_IsTrue(successRoot)){
            printf("%s\n",messageRoot->valuestring) ;    
        }else{
            perror("网络异常\n");
        }
    }
   
    return realsize;
}

void sendConfigRequest(){
    //1.读取当前文件目录下面的config.ini  获取 devinfo_path 地址
    GKeyFile *configiniPath=g_key_file_new();
    if(!g_key_file_load_from_file(configiniPath,"./config.ini",G_KEY_FILE_NONE,NULL)){
      g_warning("load config.ini error!");
      return -1;
    }
    gchar *path =g_key_file_get_string(configiniPath,"config","devinfo_path",NULL);
    g_key_file_free(configiniPath);

    //2.去devinfo_path指定的文件中读取 ip 和 地址
    GKeyFile *configPath =  g_key_file_new();
    if(!g_key_file_load_from_file(configPath,path,G_KEY_FILE_NONE,NULL)){
      g_warning("load config.ini error!");
      return -1;
    }
    gchar *gatewayip= g_key_file_get_string(configPath,"config","gatewayip",NULL);
    gchar *location= g_key_file_get_string(configPath,"config","location",NULL);
    g_key_file_free(configPath);
    

    char *url ="http://%s/config.json?sn=1205556&location=%s";
    char * realUrl= calloc(1,100);
    sprintf(realUrl,url,gatewayip,location);
    printf("request address:%s\n",realUrl);

    sendGetRequest(realUrl,configCallback);
}